interface IItem {
    ctx: unknown // this
    func: Function
}

/**
 * 事件管理器
 */
export default class EventMgr{
    static _instance: EventMgr;

    static get instance() {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new EventMgr();
        return this._instance;
    }
    // 事件存储Map
    private eventDic: Map<string, Array<IItem>> = new Map()

    // 注册对应事件
    on(eventName: string, func: Function, ctx?: unknown) {
        if (this.eventDic.has(eventName)) {
            this.eventDic.get(eventName).push({ func, ctx })
        } else {
            this.eventDic.set(eventName, [{ func, ctx }])
        }
    }

    // 注销对应事件
    off(eventName: string, func: Function) {
        if (this.eventDic.has(eventName)) {
            const index = this.eventDic.get(eventName).findIndex(i => i.func === func)
            index > -1 && this.eventDic.get(eventName).slice(index, 1)
        }
    }

    // 执行对应事件
    emit(eventName: string, ...params: unknown[]) {
        if (this.eventDic.has(eventName)) {
            this.eventDic.get(eventName).forEach((i: IItem) => {
                if (i.ctx) {
                    i.func.apply(i.ctx, params)
                } else {
                    i.func(...params)
                }
            })
        }
    }

    // 清理事件内容
    clear() {
        this.eventDic.clear()
    }
}


